Ext.ns('AIR2.UI');
/***************
 * AIR2 Form Editor Component
 *
 * A simple FormPanel with some custom start/end edit events. Used as the row
 * editor in AIR2.UI.LiveEditor. After creating one (don't render it to
 * anything), call startEdit(), passing in a record to edit and an element to
 * replace with the form.
 *
 * @class AIR2.UI.FormEditor
 * @extends Ext.form.FormPanel
 * @xtype air2formeditor
 * @cfg {Array} items
 *   Ext.form.FormPanel items
 * @event beforeedit(formpanel, records)
 * @event beforesave(formpanel, records)
 * @event aftersave(formpanel, records)
 * @event canceledit(formpanel, records)
 *
 */
AIR2.UI.FormEditor = function(config) {
    this.addEvents('beforeedit');
    this.addEvents('beforesave');
    this.addEvents('aftersave');
    this.addEvents('canceledit');

    // add save/cancel buttons in toolbar
    config.bbar = [{
        xtype: 'air2button',
        air2type: 'SAVE',
        air2size: 'MEDIUM',
        text: 'Save',
        scope: this,
        handler: function() {this.endEdit(true)}
    },'   ',{
        xtype: 'air2button',
        air2type: 'CANCEL',
        air2size: 'MEDIUM',
        text: 'Cancel',
        scope: this,
        handler: function() {this.endEdit(false)}
    }];

    // call parent constructor
    AIR2.UI.FormEditor.superclass.constructor.call(this, config);
}
Ext.extend(AIR2.UI.FormEditor, Ext.form.FormPanel, {
    cls: 'air2-panel-editinplace',
    unstyled: true,
    style: 'display: block',
    labelWidth: 75,
    defaults: {
        style: {width: '96%'}
    },
    startEdit: function(rec, replaceEl) {
        var el = Ext.get(replaceEl);
        el.setHeight(el.getHeight()); // to avoid stuttering
        el.update('');
        this.render(el);
        el.setHeight('auto');

        this.editingRec = rec;
        this.getForm().loadRecord(rec);
        this.fireEvent('beforeedit', this, rec);
    },
    endEdit: function(doSave) {
        var store = this.editingRec.store;
        if (doSave) {
            if (!this.getForm().isValid()) return; // validate form

            this.getForm().updateRecord(this.editingRec);
            this.fireEvent('beforesave', this, this.editingRec);
            if (this.editingRec.dirty) {
                this.el.mask('Saving...');
                store.save();
                store.on('save', function() {
                    this.el.unmask();
                    this.fireEvent('aftersave', this, this.editingRec);
                    this.destroy();
                }, this, {single: true});
            } else {
                this.fireEvent('canceledit', this, this.editingRec);
            }
        } else {
            this.editingRec.reject(true); //silent
            if (this.editingRec.phantom) store.remove(this.editingRec);
            this.fireEvent('canceledit', this, this.editingRec);
            this.destroy();
        }
    }
});
Ext.reg('air2formeditor', AIR2.UI.FormEditor);